#include "clientgame.h"
#include <QDomDocument>
#include <QDomNodeList>
#include <QDomElement>
#include <QFile>
#include <QStringList>
#include <QDebug>


ClientGame::ClientGame()
{

}

ClientGame::~ClientGame()
{
   qDebug() << "~ClientGame";
   foreach (ClientEntity *e, entities)
   {
      delete e;
   }
   entities.clear();
}


PathListType ClientGame::paths()
{
   return mPaths;
}


void ClientGame::mapChange(const QString &filename)
{
   parseMapFile(filename);
}


void ClientGame::parseMapFile(const QString &filename)
{
   QDomDocument doc("Map");
   QFile file(filename);
   if(!file.open(QIODevice::ReadOnly))
   {
     qDebug() << "XML: ERROR could not open map XML>" << filename;
     return;
   }
   if(!doc.setContent(&file))
   {
     qDebug() << "XML: ERROR could not read map XML (malformed?)>" << filename;
     file.close();
     return;
   }
   file.close();

   QDomNodeList nodes = doc.elementsByTagName("Path");
   for (int i=0; i<nodes.size(); ++i)
   {
      PathType path;
      QString pathName = nodes.at(i).toElement().attribute("name");

      QDomElement elem = nodes.at(i).firstChildElement("PointList");
      QStringList strList(elem.text().split(","));
      for (int j=0; j<strList.size(); ++j)
      {
         QString str = strList.at(j).simplified();
         QStringList strList2(str.split(" "));
         // Assuming tag values are paired correctly...
         path.append(QPoint(strList2.at(0).toInt(), strList2.at(1).toInt()));
      }
      //qDebug() << "Game::parseMapFile: path=" << pathName;
      mPaths.insert(pathName, path);
   }
}


ClientEntity* ClientGame::addEntity(const ClientEntity &entity)
{
   if (entities.contains(entity.id))
   {
      qDebug() << "ClientGame::addEntity: id already exists" << ((int)entity.id);
      return entities.value(entity.id);
   }
   else
   {
      ClientEntity *e = new ClientEntity(entity);
      entities.insert(entity.id, e);
      qDebug() << "ClientGame::addEntity id=" << e->id << "loc=" << e->pos;
      return e;
   }
}

void ClientGame::removeEntity(const qint32 id)
{
   qDebug() << "ClientGame::removeEntity id=" << id;
   if (entities.contains(id))
   {
      ClientEntity *e = entities[id];
      entities.remove(id);
      delete e;
   }
}
/*
void ClientGame::updateEntities(ClientEntity::ClientEntityListType entityUpdates)
{
   foreach (ClientEntity *e, entityUpdates)
   {
      if (entities.contains(e->id))
      {
         //qDebug() << "ClientGame::updateEntities: updating id=" << ((int)e->id) << "pos" << e->pos;
         entities.value(e->id)->pos = e->pos;
      }
   }
}
*/
